package com.gexiaobao.pigeon.ui.organizer.fragment

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.text.InputType
import android.view.inputmethod.EditorInfo
import androidx.core.widget.addTextChangedListener
import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.LinearLayoutManager
import com.gexiaobao.pigeon.R
import com.gexiaobao.pigeon.app.base.BaseFragment
import com.gexiaobao.pigeon.app.ext.hideSoftKeyboard
import com.gexiaobao.pigeon.app.ext.init
import com.gexiaobao.pigeon.app.ext.initFooter
import com.gexiaobao.pigeon.app.ext.loadListData
import com.gexiaobao.pigeon.app.ext.loadServiceInit
import com.gexiaobao.pigeon.app.ext.showLoading
import com.gexiaobao.pigeon.app.ext.showMessage
import com.gexiaobao.pigeon.app.model.param.CreateDeviceParams
import com.gexiaobao.pigeon.app.model.param.ModifyDeviceInfoParams
import com.gexiaobao.pigeon.app.util.RxToast
import com.gexiaobao.pigeon.app.util.Util
import com.gexiaobao.pigeon.app.weight.recycleview.SpaceItemDecoration
import com.gexiaobao.pigeon.databinding.FragmentDeviceListBinding
import com.gexiaobao.pigeon.permissions.PermissionInterceptor
import com.gexiaobao.pigeon.ui.adapter.DeviceInfoAdapter
import com.gexiaobao.pigeon.ui.dialog.RxDialogAddDevice
import com.gexiaobao.pigeon.viewmodel.MyDeviceViewModel
import com.gexiaobao.pigeon.viewmodel.request.RequestDeviceViewModel
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import com.kingja.loadsir.core.LoadService
import com.yzq.zxinglibrary.android.CaptureActivity
import com.yzq.zxinglibrary.common.Constant
import me.hgj.jetpackmvvm.ext.nav
import me.hgj.jetpackmvvm.ext.util.setOnclickNoRepeat

/**
 * @Author      : hxw
 * @Date        : 2023/6/1 12:19
 * @Describe    : 组织方-会员的设备列表
 */
class FragmentDeviceList : BaseFragment<MyDeviceViewModel, FragmentDeviceListBinding>() {

    private var shedNo = ""

    private val mAdapter: DeviceInfoAdapter by lazy { DeviceInfoAdapter(arrayListOf()) }

    //界面状态管理者
    private lateinit var loadsir: LoadService<Any>
    private lateinit var dialog: RxDialogAddDevice
    private val requestDeviceViewModel: RequestDeviceViewModel by viewModels()

    override fun initView(savedInstanceState: Bundle?) {

        mDatabind.includeSearch.etSearch.hint = "请输入棚号查询"

        mDatabind.includeSearch.etSearch.inputType = InputType.TYPE_CLASS_NUMBER

        mDatabind.includeSearch.etSearch.setOnEditorActionListener { _, i, _ ->
            when (i) {
                EditorInfo.IME_ACTION_SEARCH ->
                    searchMemberList()

                else -> {}
            }
            false
        }

        mDatabind.includeSearch.etSearch.addTextChangedListener {
            shedNo = it.toString().trim()
            if (shedNo.isEmpty()) {
                hideSoftKeyboard(activity)
                loadsir.showLoading()
                requestDeviceViewModel.getMemberDeviceList(true, "", shedNo)
            }
        }

        mDatabind.layoutList.swipeRecyclerView.init(LinearLayoutManager(context), mAdapter).let {
            it.addItemDecoration(SpaceItemDecoration(0, Util.dp2px(context, 5f)))
            it.initFooter {
                //触发加载更多时请求数据
                requestDeviceViewModel.getMemberDeviceList(false, "", shedNo)
            }
        }
        //状态页配置
        loadsir = loadServiceInit(mDatabind.layoutList.swipeRefreshLayout) {
            //点击重试时触发的操作
            loadsir.showLoading()
            requestDeviceViewModel.getMemberDeviceList(true, "", shedNo)
        }

        mDatabind.layoutList.swipeRefreshLayout.init {
            loadsir.showLoading()
            requestDeviceViewModel.getMemberDeviceList(true, "", shedNo)
        }

        mAdapter.setOnModifyClickListener(object : DeviceInfoAdapter.MyModifyClickListener {
            override fun clickModifyListener(imsi: String, id: Int) {
                showAddDeviceDialog(1, imsi, id)
            }
        })

        mAdapter.setOnDeleteClickListener(object : DeviceInfoAdapter.MyDeleteClickListener {
            override fun clickDeleteListener(id: Int) {
                showLoading(getString(R.string.loading))
                requestDeviceViewModel.deleteMemberDevice(id.toString())
            }
        })

        mAdapter.addChildClickViewIds(R.id.tv_org_add_device)
        mAdapter.setOnItemChildClickListener { _, _, position ->
            showAddDeviceDialog(2, "", position)
        }
    }

    private fun searchMemberList() {
        loadsir.showLoading()
        requestDeviceViewModel.getMemberDeviceList(true, "", shedNo)
    }


    override fun lazyLoadData() {
        super.lazyLoadData()
        loadsir.showLoading()
        requestDeviceViewModel.getMemberDeviceList(true, "", shedNo)
    }

    override fun createObserver() {
        super.createObserver()
        requestDeviceViewModel.deviceList.observe(viewLifecycleOwner) {
            loadListData(it, mAdapter, loadsir, mDatabind.layoutList.swipeRecyclerView, mDatabind.layoutList.swipeRefreshLayout)
        }

        requestDeviceViewModel.createDeviceResult.observe(viewLifecycleOwner) {
            dismissLoading()
            if (it.isSuccess) {
                loadsir.showLoading()
                requestDeviceViewModel.getMemberDeviceList(true, "", shedNo)
            } else {
                RxToast.showToast(it.errorMsg)
            }
        }

        requestDeviceViewModel.deleteDeviceResult.observe(viewLifecycleOwner) {
            dismissLoading()
            if (it.isSuccess) {
                loadsir.showLoading()
                requestDeviceViewModel.getMemberDeviceList(true, "", shedNo)
            } else {
                RxToast.showToast(it.errorMsg)
            }
        }

        requestDeviceViewModel.updateDeviceResult.observe(viewLifecycleOwner) {
            dismissLoading()
            if (it.isSuccess) {
                loadsir.showLoading()
                requestDeviceViewModel.getMemberDeviceList(true, "", shedNo)
            } else {
                RxToast.showToast(it.errorMsg)
            }
        }
    }

    override fun onBindViewClick() {
        super.onBindViewClick()
        setOnclickNoRepeat(mDatabind.includeSearch.tvSearch) {
            when (it) {
                mDatabind.includeSearch.tvSearch -> {
                    if (shedNo.isEmpty()) {
                        RxToast.showToast("请输入要查询的棚号")
                        return@setOnclickNoRepeat
                    }
                    loadsir.showLoading()
                    requestDeviceViewModel.getMemberDeviceList(true, "", shedNo)
                }
            }
        }
    }

    private fun showAddDeviceDialog(type: Int, imsi: String, inValue: Int) {//type：1修改，2添加
        dialog = RxDialogAddDevice(context)
        if (type == 1) {
            dialog.setCode(imsi)
            dialog.setSele(imsi.length)
        }
        dialog.setScanListener {
            permissionRequest()
        }
        dialog.setSureListener {
            val code = dialog.getCode()
            if (code.isEmpty()) {
                RxToast.showToast("设备号不可为空")
                return@setSureListener
            }
            if (code.length < 15) {
                showMessage("设备号格式不正确")
                return@setSureListener
            }
            if (code.substring(0, 4) != "4600") {
                RxToast.showToast("设备号必须4600开头")
                return@setSureListener
            }

            dialog.dismiss()
            showLoading(getString(R.string.loading))
            if (code.isEmpty()) {
                RxToast.showToast("设备号格式错误")
                return@setSureListener
            }
            when (type) {
                1 -> {
                    val modifyBody = ModifyDeviceInfoParams(
                        id = inValue,
                        imsi = code
                    )
                    requestDeviceViewModel.updateMemberDevice(modifyBody)
                }

                2 -> {
                    val createBody = CreateDeviceParams(
                        imsi = code,
                        memberId = mAdapter.data[inValue].memberId.toInt()
                    )
                    requestDeviceViewModel.createDevice(createBody)
                }
            }
        }
        dialog.setFullScreenWidth()
        dialog.show()
    }

    private fun permissionRequest() {
        XXPermissions.with(this)
            .permission(Permission.CAMERA)
            .interceptor(PermissionInterceptor())
            .request { _, allGranted ->
                if (allGranted) {
                    val intent = Intent(activity, CaptureActivity::class.java)
                    startActivityForResult(intent, 11022)
                } else {
                    nav().navigateUp()
                }
            }
    }

    @Deprecated("Deprecated in Java")
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        // 扫描二维码/条码回传
        if (requestCode == 11022 && resultCode == Activity.RESULT_OK) {
            val content = data!!.getStringExtra(Constant.CODED_CONTENT)
            content?.let { dialog.setCode(it) }
        }
    }

    companion object {

        private var userId = 0
        fun newInstance(id: Int): FragmentDeviceList {
            userId = id
            return FragmentDeviceList()
        }
    }
}